/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ranophoenix.osgijee.webclient.impl.cdi;

import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import ranophoenix.osgijee.core.ModuleExtension;
import ranophoenix.osgijee.webclient.impl.cdi.qualifiers.Destroyed;
import ranophoenix.osgijee.webclient.impl.cdi.qualifiers.Initialized;

/**
 *
 * @author ranophoenix
 */
public class ModuleExtensionListener implements ServiceListener {

    private BundleContext m_context;
    @Inject
    @Initialized
    private Event<ModuleExtension> modExtAddedEvent;
    @Inject
    @Destroyed
    private Event<ModuleExtension> modExtRemovedEvent;
    
    @Inject
    private ApplicationBean appBean;
    
    @Inject
    public void initialize(BundleContext bc) {
        m_context = bc;
    }

    public void serviceChanged(ServiceEvent event) {
        Object o = m_context.getService(event.getServiceReference());

        if (o instanceof ModuleExtension) {
            ModuleExtension me = (ModuleExtension) o;
            switch (event.getType()) {
                case ServiceEvent.REGISTERED:
                    //modExtAddedEvent.fire(me);
                    appBean.afterAddModuleExtension(me);
                    break;
                case ServiceEvent.UNREGISTERING:
                    //modExtRemovedEvent.fire(me);
                    appBean.beforeRemoveModuleExtension(me);
                    break;
                default:
                    break;
            }
        }
    }
}
